#include <fcntl.h>
#include <unistd.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
  int pipefd[2] = {0};
  if (pipe(pipefd) != 0)
  {
    cerr << "pipe error!" << endl;
    return 1;
  }

  pid_t id = fork();
  if (id == 0)
  {
    sleep(1);
    // child,read,close write
    close(pipefd[1]);
    char buff[1024];
    while (1)
    {
      ssize_t s = read(pipefd[0], (void *)buff, sizeof buff);
      if (s > 0)
      {
        cout << "child process echo:" << buff << endl;
      }
      else if (s == 0) // 表示读取结束，因为写端关闭
      {
        cout << "read end" << endl;
        exit(0);
      }
      else
      {
        cout << "read error" << endl;
        exit(-1);
      }
    }
  }

  close(pipefd[0]);
  // parent,write,close read
  while (1)
  {
    char buff[1024] = "message from parent process---";
    write(pipefd[1], buff, sizeof buff);
    sleep(2);
  }
  return 0;
}
